const md5 = require('md5-node');

const X2JS = require('x2js');

const sha1 = require('node-sha1');

const SMSClient = require('@alicloud/sms-sdk')
let OSS = require('ali-oss');


module.exports = app => {
    const { router, logger } = app;

    app.beforeStart(async () => {
        const start = Date.now();
        logger.info('接口初始化工作开始执行...');
        // const apiarr = [];
        // const stack = router.stack;
        // for(let i = 0, j = stack.length; i < j; i++){
        //     let path = stack[i].path;
        //     if(path == '/') continue;
        //     if(path.indexOf(':') != -1){
        //         path = path.substring(0,path.indexOf(':')-1);
        //     }
        //     let api = {
        //         'url' : path,
        //         'md5' : md5(path)
        //     }
        //     apiarr.push(api);
        // }
        // await app.redis.set('qunmeng_api_' + app.env, JSON.stringify({'api' : apiarr}));


        //初始化短信
        const accessKeyId = 'LTAI5LEHmQC6MDYW'
        const secretAccessKey = 'XVX0JV5kwl3NcbCEYFqSgeI4PmzItd'
        //初始化sms_client
        let smsClient = new SMSClient({accessKeyId, secretAccessKey})
        app['smsClient'] = smsClient;

        let ossClient = new OSS({
          region: 'oss-cn-qingdao',
          accessKeyId,
          'accessKeySecret' : secretAccessKey,
          bucket: 'qunmeng-oss'
        });

        app['oss'] = ossClient;

        //json/xml 互转
        app['x2js'] = new X2JS();

        //md5
        app['md5'] = md5;

        //sha1
        app['sha1'] = sha1;

        logger.info('启动耗时:', Date.now() - start);
    });

    app.on('response', ctx => {
        // if(ctx.body['errcode'] === 0){
        //     logger.info(apiinfo(ctx));
        // }
    });

    app.on('error', (err, ctx) => {
        // const api_info = apiinfo(ctx);
        // api_info['z_exception'] = err;
        // logger.info(api_info);
    });

    function apiinfo(ctx) {
        const req = ctx.request.header;
        const rep = ctx.response.header;
        for(let k in rep){
            req[k] = rep[k];
        }
        let data = JSON.stringify(ctx.body.data);
        if(data != undefined){
            if(data.length > 2000){
                data = '结果内容过大，不打印结果。';
            }
        }else{
            data = [];
        }
        const api_info = {
            'enviro' : ctx.app.env,
            '_id' : Date.now(),
            '_collectionid' : ctx.request.url,
            'url' : ctx.request.url,
            'spend' : Date.now() - ctx.starttime,
            'header' : JSON.stringify(req),
            'params' : ctx.query,
            'x_result' : data
        };
        return api_info;
    }

};